package com.djx.commons.config.shiro;


import com.alibaba.fastjson.JSON;
import com.djx.commons.response.Result;
import com.djx.commons.response.ResultCode;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

//表单拦截器 autch就是FormAuthenticationFilter的实例
public class CORSAuthenticationFilter extends FormAuthenticationFilter {


    public CORSAuthenticationFilter(){
        super();
    }

    //请求是否被允许访问，此方法在AccessControlFilter是抽象方法，被AuthenticatingFilter重写
    //调用父类AuthenticationFilter的方法判断 当前用户是否已认证过,并且判断请求url是不是配置的loginurl
    //如果是一个没认证过的请求，isAccessAlowed肯定是false，执行onAccessDefined方法
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
            return true;
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    //如果请求是登录请求，发起登录，如果不是就保存原请求，并重定向到登录url ，saveRequestAndRedirectToLogin
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse res = (HttpServletResponse)response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setStatus(HttpServletResponse.SC_OK);
        res.setCharacterEncoding("UTF-8");
        PrintWriter writer = res.getWriter();
        String s = JSON.toJSONString(new Result(ResultCode.LOGIN_TIME_OUT));
        writer.write(s);
        writer.close();
        return false;
    }
}